<?php

namespace app\common\model;

/**
 * @property string $code 通知系统编码
 * @property string $name 模板名称
 * @property string $notice_tpl_id
 * @property string $sms_code 阿里云短信模板编号
 * @property string $status 0=禁用 1=启用
 * @property string $template 模板
 * @property string $title 标题或签名
 * @property string $type 通知类型
 */
class NoticeTpl extends BaseModel
{
    // 表名
    protected $name = 'notice_tpl';
    protected $pk   = 'notice_tpl_id';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';

    protected $type = [

    ];

    protected $readonly = [

    ];

    protected $hidden = [

    ];


    // 追加属性
    protected $append = [

    ];


    /**
     * 模板转实际发送数据
     *
     * @access private
     *
     * @param string $code 通知编码
     * @param array  $data 内部提交数据
     *
     * @return mixed
     */
    public function templateToSendContent(string $type, $data)
    {
        $realValue = function ($item_name, $replace_name) use ($data) {
            $value = $data[$replace_name] ?? $item_name;
            return $value;
        };
        // 填充可用变量实际内容
        $noticeItem = [];
        $this->noticeItem = NoticeItem::build()->where('type', '=', $type)
                                      ->column('replace_name', 'item_name');

        foreach ($this->noticeItem as $key => $value) {
            $noticeItem[$value] = $realValue($key, $value);
        }
        // 从模板中获取需要替换的变量
        $replaceItem = [];
        $template = NoticeTpl::build()
                             ->where('type', $type)
                             ->value('template');
        if (false === preg_match_all('/\{([^\}]+)\}/', $template, $replaceItem)) {
            return false;
        }
        $result = '';
        if (!empty($replaceItem[0])) {
            $emailData = $template;
            foreach ($replaceItem[0] as $value) {
                $v = preg_replace('/[\{\}]/', '', $value);
                if (isset($this->noticeItem[$v])) {
                    $emailData = str_replace($value, $noticeItem[$this->noticeItem[$v]], $emailData);
                }
            }
            $result = $emailData;
        }
        return $result;
    }

}
